import type { 
  MarkAPI, 
  Conversation, 
  Message, 
  FileInfo,
  MessageRole 
} from '../types/mark-api';

// 事件处理器类型定义
type EventHandler<T = unknown> = (data: T) => void;

/**
 * Mark API 客户端类
 * 提供对C# Mark API的TypeScript包装
 */
export class MarkApiClient {
  private api: MarkAPI;

  constructor() {
    if (typeof window === 'undefined' || !window.MarkAPI) {
      throw new Error('Mark API not available. Make sure the application is running in a MAUI WebView.');
    }
    this.api = window.MarkAPI;
    this.setupEventHandlers();
  }

  /**
   * 设置事件处理器
   */
  private setupEventHandlers() {
    // 新消息事件处理
    window.onNewMessage = (message: Message) => {
      console.log('New message received:', message);
      this.emit('newMessage', message);
    };

    // 对话更新事件处理
    window.onConversationUpdated = (conversation: Conversation) => {
      console.log('Conversation updated:', conversation);
      this.emit('conversationUpdated', conversation);
    };

    // 错误事件处理
    window.onError = (error: { message: string }) => {
      console.error('API error:', error);
      this.emit('error', error);
    };
  }

  // 简单的事件发射器
  private eventHandlers: { [key: string]: EventHandler[] } = {};

  public on<T = unknown>(event: string, handler: EventHandler<T>) {
    if (!this.eventHandlers[event]) {
      this.eventHandlers[event] = [];
    }
    this.eventHandlers[event].push(handler as EventHandler);
  }

  public off<T = unknown>(event: string, handler: EventHandler<T>) {
    if (this.eventHandlers[event]) {
      this.eventHandlers[event] = this.eventHandlers[event].filter(h => h !== handler);
    }
  }

  private emit<T = unknown>(event: string, data: T) {
    if (this.eventHandlers[event]) {
      this.eventHandlers[event].forEach(handler => handler(data));
    }
  }

  /**
   * 创建新对话
   */
  async createConversation(userId: string, title: string, description?: string): Promise<Conversation> {
    const response = await this.api.createConversation(userId, title, description);
    if (!response.success || !response.data) {
      throw new Error(response.message || 'Failed to create conversation');
    }
    return response.data;
  }

  /**
   * 获取用户的所有对话
   */
  async getUserConversations(userId: string): Promise<Conversation[]> {
    const response = await this.api.getUserConversations(userId);
    if (!response.success || !response.data) {
      throw new Error(response.message || 'Failed to get conversations');
    }
    return response.data;
  }

  /**
   * 发送消息
   */
  async sendMessage(
    conversationId: string, 
    content: string, 
    role: MessageRole = 'user',
    modelId?: string
  ): Promise<Message> {
    const response = await this.api.sendMessage(conversationId, content, role, modelId);
    if (!response.success || !response.data) {
      throw new Error(response.message || 'Failed to send message');
    }
    return response.data;
  }

  /**
   * 获取对话中的所有消息
   */
  async getConversationMessages(conversationId: string): Promise<Message[]> {
    const response = await this.api.getConversationMessages(conversationId);
    if (!response.success || !response.data) {
      throw new Error(response.message || 'Failed to get messages');
    }
    return response.data;
  }

  /**
   * 生成AI响应
   */
  async generateResponse(conversationId: string, modelId: string): Promise<Message> {
    const response = await this.api.generateResponse(conversationId, modelId);
    if (!response.success || !response.data) {
      throw new Error(response.message || 'Failed to generate response');
    }
    return response.data;
  }

  /**
   * 发送消息并自动生成回复
   */
  async sendMessageAndGenerate(
    conversationId: string,
    content: string,
    modelId: string
  ): Promise<{ userMessage: Message; aiMessage: Message }> {
    // 先发送用户消息
    const userMessage = await this.sendMessage(conversationId, content, 'user', modelId);
    
    // 然后生成AI回复
    const aiMessage = await this.generateResponse(conversationId, modelId);
    
    return { userMessage, aiMessage };
  }

  /**
   * 上传文件
   */
  async uploadFile(userId: string, file: File): Promise<FileInfo> {
    const response = await this.api.uploadFile(userId, file);
    if (!response.success || !response.data) {
      throw new Error(response.message || 'Failed to upload file');
    }
    return response.data;
  }
}

/**
 * 创建Mark API客户端实例
 */
export function createMarkApiClient(): MarkApiClient {
  return new MarkApiClient();
}

/**
 * 全局Mark API客户端实例
 */
let globalClient: MarkApiClient | null = null;

/**
 * 获取全局Mark API客户端实例
 */
export function getMarkApiClient(): MarkApiClient {
  if (!globalClient) {
    globalClient = new MarkApiClient();
  }
  return globalClient;
}

// 默认导出
export default MarkApiClient; 